package park.gz.com.parkingfee.fragment;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import park.gz.com.parkingfee.R;
import park.gz.com.parkingfee.activity.MainActivity;
import park.gz.com.parkingfee.activity.MyAppcation;
import park.gz.com.parkingfee.bean.CarInfo;
import park.gz.com.parkingfee.until.GetImei;
import park.gz.com.parkingfee.until.ShareUtil;

/**
 * Created by Administrator on 2017-03-15.
 */

public class ParkfeeFragment extends BaseFragment {

    @Bind(R.id.tx_carnumber)
    TextView txCarnumber;
    @Bind(R.id.input_carnumber)
    EditText inputCarnumber;
    @Bind(R.id.rl_carnum)
    RelativeLayout rlCarnum;
    @Bind(R.id.btn_query)
    Button btnQuery;
    @Bind(R.id.img_car)
    ImageView imgCar;
    @Bind(R.id.address)
    TextView address;
    @Bind(R.id.intime)
    TextView intime;
    @Bind(R.id.longtime)
    TextView longtime;
    @Bind(R.id.getfee)
    TextView getfee;
    @Bind(R.id.btn_ok)
    Button btnOk;
    @Bind(R.id.outapplication)
    TextView outapplication;
    @Bind(R.id.ly_address)
    LinearLayout lyAddress;
    @Bind(R.id.ly_intime)
    LinearLayout lyIntime;
    @Bind(R.id.ly_parktime)
    LinearLayout lyParktime;
    @Bind(R.id.btn_free)
    Button btnFree;
    @Bind(R.id.tx_car)
    TextView txcar;
    @Bind(R.id.type)
    TextView type;
    private List<CarInfo> carInfoList;//根据车牌号查询到的数据
    private CarInfo carInfo;//模糊查询到多条史选定的某一条
    private AlertDialog dialog;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_parkfee, container, false);
        ButterKnife.bind(this, view);
        txcar.setVisibility(View.GONE);
        return view;
    }

    @Override
    protected void iniView() {
        carInfoList = new ArrayList<CarInfo>();
        carInfo = new CarInfo();

        DisplayMetrics metrics=new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int widthPixels=metrics.widthPixels;
        int heightPixels=metrics.heightPixels;
        ViewGroup.LayoutParams params =  imgCar.getLayoutParams();
        params.height=(widthPixels-20)/16*9;
        params.width =widthPixels-20;
        imgCar.setLayoutParams(params);
    }

    @Override
    protected void iniData() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    /**
     * 根据车牌号查询收费信息
     */
    private void car_fee() {

        String url = ShareUtil.getstringvalue(getActivity(),"baseurl") + "/api/v2/car_fee";
        RequestParams params = new RequestParams(url);
        params.addParameter("car_no", inputCarnumber.getText().toString());//车号
        params.addParameter("terminal_type", "2");//终端类型（岗亭终端1，手机APP2，触摸自助3，微信小程序4）
        params.addParameter("garage_code", "");//车库编号：除微信小程序外，其他类型不需要
        params.addParameter("controller_sn", GetImei.getphoneimei(getActivity()));//终端编号，微信小程序不需要
        params.addParameter("access_token",ShareUtil.getstringvalue(getActivity(),"access_token"));
        Log.e("duzhijuan", params + "");
        x.http().get(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.getString("ref"))) {//设备未注册
                        Toast.makeText(getActivity(), jsonObject.getString("msg"), Toast.LENGTH_LONG).show();
                    } else if ("0".equals(jsonObject.getString("ref"))) {//搜索成功
                        carInfoList.clear();
                        carInfoList.addAll(CarInfo.parse(jsonObject.getJSONArray("result")));
                        if (carInfoList.size() > 1) {
                            createDialog();
                        } else if (carInfoList.size() == 1 && carInfoList != null) {
                            carInfo = carInfoList.get(0);
                            address.setText(carInfo.getIn_door());
                            intime.setText(carInfo.getIn_time());
                            longtime.setText(minConvertDayHourMin(Double.parseDouble(carInfo.getParked_time())));
                            type.setText(carInfo.getCard_type());
                            getfee.setText("收费:￥" + carInfo.getFact_pre_fee());
                            Glide.with(getActivity()).
                                    load(ShareUtil.getstringvalue(getActivity(),"baseurl") +"/car_images/"+ carInfo.getIn_time().split(" ")[0] + "/" + carInfo.getIn_image()).
                                    asBitmap().//强制处理为bitmap
                                    placeholder(R.drawable.ic_img_car).//加载中显示的图片
                                    error(R.drawable.ic_img_car).//加载失败时显示的图片
                                    into(imgCar);//显示到目标View中
                            txcar.setVisibility(View.VISIBLE);
                            txcar.setText(carInfo.getCar_no());
                        }
                    } else {
                        Toast.makeText(getActivity(), jsonObject.getString("msg"), Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("my", "onError" + ex.toString());
                Toast.makeText(getActivity(),"请求失败,请确认您的服务是否有误",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Log.e("my", "onCancelled" + cex.toString());
                Toast.makeText(getActivity(),"请求失败,请确认您的服务是否有误",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                Log.e("my", "onFinished");
            }

        });
    }

    @OnClick({R.id.btn_query, R.id.btn_ok,R.id.outapplication,R.id.btn_free})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_query:
                car_fee();
                break;
            case R.id.btn_ok:
                if (carInfo == null) {
                    Toast.makeText(getActivity(), "车辆信息为空！", Toast.LENGTH_LONG).show();
                } else{
                    if (!"0".equals(carInfo.getFact_pre_fee())){
                        confirm_fee(carInfo.getFact_pre_fee());
                    }else{
                        Toast.makeText(getActivity(),"本次通车无需缴费",Toast.LENGTH_LONG).show();
                    }
                }


                break;
            case R.id.outapplication:
                Intent intent = new Intent(getActivity(), MainActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_free:
                if (!"0".equals(carInfo.getFact_pre_fee())){
                    confirm_fee("0");
                }else{
                    Toast.makeText(getActivity(),"本次通车无需缴费",Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    /**
     * 选定车辆
     */
    private void createDialog() {
        dialog = new AlertDialog.Builder(getActivity()).create();
        View dialogView = LayoutInflater.from(getActivity()).inflate(R.layout.activity_dialog, null);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setView(dialogView, 0, 0, 0, 0);
        dialog.show();
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);//WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE|(开启)WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
        MyAdapter adapter = new MyAdapter();
        final RecyclerView recyclerView = (RecyclerView) dialogView.findViewById(R.id.dialog_recyclerview);
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        recyclerView.setAdapter(adapter);

    }

    class MyAdapter extends RecyclerView.Adapter<MyHolder> {

        @Override
        public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View item = LayoutInflater.from(getActivity()).inflate(R.layout.choicecaritem, parent, false);
            MyHolder myHolder = new MyHolder(item);
            return myHolder;
        }

        @Override
        public void onBindViewHolder(MyHolder holder, final int position) {
            holder.carnumber.setText(carInfoList.get(position).getCar_no());
            holder.carnumber.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    carInfo = carInfoList.get(position);
                    dialog.dismiss();
                    address.setText(carInfo.getIn_door());
                    intime.setText(carInfo.getIn_time());
                    type.setText(carInfo.getCard_type());
                    longtime.setText(minConvertDayHourMin(Double.parseDouble(carInfo.getParked_time())));
                    getfee.setText("收费:￥" + carInfo.getFact_pre_fee());

                    Glide.with(getActivity()).
                            load(ShareUtil.getstringvalue(getActivity(),"baseurl") +"/car_images/"+ carInfo.getIn_time().split(" ")[0] + "/" + carInfo.getIn_image()).
                            asBitmap().//强制处理为bitmap
                            placeholder(R.drawable.ic_img_car).//加载中显示的图片
                            error(R.drawable.ic_img_car).//加载失败时显示的图片
                            into(imgCar);//显示到目标View中
                    txcar.setVisibility(View.VISIBLE);
                    txcar.setText(carInfo.getCar_no());
                }
            });
        }

        @Override
        public int getItemCount() {
            return carInfoList.size();
        }

        @OnClick(R.id.carnumber)
        public void onClick() {
        }
    }

    class MyHolder extends RecyclerView.ViewHolder {

        @Bind(R.id.carnumber)
        TextView carnumber;

        public MyHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public static String minConvertDayHourMin(Double min) {
        String html = "0分";
        if (min != null) {
            Double m = (Double) min;
            String format;
            Object[] array;
            Integer days = (int) (m / (60 * 24));
            Integer hours = (int) (m / (60) - days * 24);
            Integer minutes = (int) (m - hours * 60 - days * 24 * 60);
            if (days > 0) {
                format = "%1$,d天%2$,d时%3$,d分";
                array = new Object[]{days, hours, minutes};
            } else if (hours > 0) {
                format = "%1$,d时%2$,d分";
                array = new Object[]{hours, minutes};
            } else {
                format = "%1$,d分";
                array = new Object[]{minutes};
            }
            html = String.format(format, array);
        }
        return html;
    }

    /**
     * 确认收费
     */
    private void confirm_fee(String fact_fee) {

        String url = ShareUtil.getstringvalue(getActivity(),"baseurl") + "/api/v2/confirm_fee";
        RequestParams params = new RequestParams(url);
        params.addParameter("pass_no", carInfo.getPass_no());//记录主键
        //params.addParameter("parked_time", carInfo.getParked_time());//停车时长
        params.addParameter("paytype","1");//缴费方式
        params.addParameter("pre_fee", fact_fee);//应收
        //params.addParameter("fact_fee", fact_fee);//实收
        params.addParameter("prepay_id", carInfo.getPrepay_id());//实收
        params.addParameter("out_operator", ShareUtil.getstringvalue(getActivity(), MyAppcation.userName));//收费员
        params.addParameter("access_token",ShareUtil.getstringvalue(getActivity(),"access_token"));
        Log.e("duzhijuan", params + "");
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("0".equals(jsonObject.getString("ref"))) {
                        Toast.makeText(getActivity(), "确认收费成功", Toast.LENGTH_LONG).show();
                        inputCarnumber.setText("");
                        address.setText("- - - - - - - - - -");
                        intime.setText("- - - - - - - - - -");
                        longtime.setText("- - - - - - - - - -");
                        type.setText("- - - - - - - - - -");
                        getfee.setText("收费:￥0.0");
                        Glide.with(getActivity()).
                                load("").
                                asBitmap().//强制处理为bitmap
                                placeholder(R.drawable.ic_img_car).//加载中显示的图片
                                error(R.drawable.ic_img_car).//加载失败时显示的图片
                                into(imgCar);//显示到目标View中
                        txcar.setVisibility(View.GONE);

                    } else if ("3".equals(jsonObject.getString("ref"))) {
                        Toast.makeText(getActivity(), "收费失败，请重试", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(getActivity(), jsonObject.getString("msg"), Toast.LENGTH_LONG).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("my", "onError" + ex.toString());
                Toast.makeText(getActivity(),"请求失败,请确认您的服务是否有误",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Log.e("my", "onCancelled" + cex.toString());
                Toast.makeText(getActivity(),"请求失败,请确认您的服务是否有误",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                Log.e("my", "onFinished");
            }

        });
    }
}
